//
//  PPFoundSearchUserViewController.m
//  pickpic
//
//  Created by Jinxiao on 8/27/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPFoundSearchUserViewController.h"
#import "PPProfileViewController.h"

#import "PPFoundSearchUserTableViewCell.h"
#import "PPFollowActionView.h"
#import "PPFoundUserModel.h"

static const NSInteger kCount = 30;
@interface PPFoundSearchUserViewController ()

@end

@implementation PPFoundSearchUserViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.tableView registerNib:[UINib nibWithNibName:@"PPFoundSearchUserTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 55;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

    PPFoundUserModel *user = [self.items objectAtIndex:indexPath.row];

    ((PPFoundSearchUserTableViewCell *)cell).nickLabel.text = user.nick;
    ((PPFoundSearchUserTableViewCell *)cell).accountLabel.text = user.account;

    ((PPFoundSearchUserTableViewCell *)cell).hidden = NO;
    if ([user.relationship integerValue] == 0 || [user.relationship integerValue] == 1)
    {
        //秒友  我关注的人   已关注 //朋友  互相关注的人
        [((PPFoundSearchUserTableViewCell *)cell).followButton setTitle:@"已关注" forState:UIControlStateNormal];
        ((PPFoundSearchUserTableViewCell *)cell).followButton.backgroundColor = [UIColor colorWithRGBHex:0xffdd17];
        ((PPFoundSearchUserTableViewCell *)cell).followButton.layer.borderColor = [UIColor clearColor].CGColor;
    }
    else if ([user.relationship integerValue] == 2)
    {
        //没关系 未关注
        [((PPFoundSearchUserTableViewCell *)cell).followButton setTitle:@"关注" forState:UIControlStateNormal];
        ((PPFoundSearchUserTableViewCell *)cell).followButton.backgroundColor = [UIColor clearColor];
        ((PPFoundSearchUserTableViewCell *)cell).followButton.layer.borderColor = [UIColor colorWithRGBHex:0x323232].CGColor;
    }
    else
    {
        ((PPFoundSearchUserTableViewCell *)cell).followButton.hidden = YES;
    }

    __weak typeof(self)weakSelf = self;
    [((PPFoundSearchUserTableViewCell *)cell).followButton setActionBlock:^(UIControl *control) {
        if ([user.relationship integerValue] == 0 || [user.relationship integerValue] == 1)
        {
            //取消关注
            PPFollowActionView *actionView = [[NSBundle mainBundle] loadNibNamed:@"PPFollowActionView" owner:nil options:nil].firstObject;
            actionView.frame = CGRectMake(0, weakSelf.navigationController.view.height - actionView.height, weakSelf.navigationController.view.width, actionView.height);

            DGPopoverView *popoverView = [[DGPopoverView alloc] initWithContainerView:weakSelf.navigationController.view contentView:actionView options:DGPopoverViewAnimationOptionUpward backgroundStyle:DGPopoverViewBackgroundStyleDimmed];

            __weak typeof(popoverView) weakPopover = popoverView;
            [actionView.cancelButton setActionBlock:^(UIControl *control) {
                [weakPopover dismissAnimated:YES completion:nil];
            } forControlEvents:UIControlEventTouchUpInside];

            [actionView.unfollowButton setActionBlock:^(UIControl *control) {
                [weakPopover dismissAnimated:YES completion:^{
                    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:weakSelf.navigationController.view animated:YES];
                    [PPNetworkService unFollow:user.userID callback:^(id data, NSError *error) {
                        [hud hide:YES];
                        if (data)
                        {
                            //取消关注成功
                            user.relationship = @(2);
                            [((PPFoundSearchUserTableViewCell *)cell).followButton setTitle:@"关注" forState:UIControlStateNormal];
                            ((PPFoundSearchUserTableViewCell *)cell).followButton.backgroundColor = [UIColor clearColor];
                            ((PPFoundSearchUserTableViewCell *)cell).followButton.layer.borderColor = [UIColor colorWithRGBHex:0x323232].CGColor;
                            [weakSelf.navigationController.view toastMessage:@"操作成功" duration:1.f];

                            [[NSNotificationCenter defaultCenter] postNotificationName:PPRelationshipDidChangeNotification object:user.userID];
                        }
                        else
                        {
                            [weakSelf.navigationController.view toastMessage:error.networkPrompt duration:1.f];
                        }
                    }];

                }];
            } forControlEvents:UIControlEventTouchUpInside];

            [popoverView displayAnimated:YES completion:nil];
        }
        else if ([user.relationship integerValue] == 2)
        {
            //关注
            [MobClick event:@"141"];
            __weak typeof(self)weakSelf = self;
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
            [PPNetworkService follow:user.userID callback:^(id data, NSError *error) {
                [hud hide:YES];
                if (data)
                {
                    //关注成功
                    user.relationship = @([data integerValue]);

                    [((PPFoundSearchUserTableViewCell *)cell).followButton setTitle:@"已关注" forState:UIControlStateNormal];
                    ((PPFoundSearchUserTableViewCell *)cell).followButton.backgroundColor = [UIColor colorWithRGBHex:0xffdd17];
                    ((PPFoundSearchUserTableViewCell *)cell).followButton.layer.borderColor = [UIColor clearColor].CGColor;

                    [weakSelf.navigationController.view toastMessage:@"操作成功" duration:1.f];

                    [[NSNotificationCenter defaultCenter] postNotificationName:PPRelationshipDidChangeNotification object:user.userID];
                }
                else
                {
                    //关注失败
                    [weakSelf.navigationController.view toastMessage:error.networkPrompt duration:1.f];
                }
            }];
        }
    } forControlEvents:UIControlEventTouchUpInside];

    if(user.avatarURLString.length > 0) {
        [user.avatarURLString applyToImageView:((PPFoundSearchUserTableViewCell *)cell).avatarView];
     } else {
         ((PPFoundSearchUserTableViewCell *)cell).avatarView.image = [UIImage imageNamed:@"icon-person-70"];
     }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [MobClick event:@"140"];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    PPFoundUserModel *user = [self.items objectAtIndex:indexPath.row];

    PPProfileViewController *profileViewController = [[PPProfileViewController alloc] init];
    profileViewController.userID = user.userID;
    [self.navigationController pushViewController:profileViewController animated:YES];
}

#pragma mark - Timeline

- (void)fetchNewItems {
    [super fetchNewItems];

    __weak typeof(self)weakSelf = self;
    [PPNetworkService searchUserWithPage:@(1) limit:@(kCount) keyword:_keyword callback:^(id data, NSError *error) {
        __strong typeof(weakSelf)strongSelf = weakSelf;

        if(strongSelf == nil) {
            return;
        }

        [strongSelf didReceiveNewResult:data ? : error];
    }];
}

- (void)fetchMoreItems {
    [super fetchMoreItems];

    __weak typeof(self)weakSelf = self;
    [PPNetworkService searchUserWithPage:@(self.items.count/kCount + 1) limit:@(kCount) keyword:_keyword callback:^(id data, NSError *error) {
        __strong typeof(weakSelf)strongSelf = weakSelf;

        if(strongSelf == nil) {
            return;
        }

        [strongSelf didReceiveMoreResult:data ? : error];
    }];
}

- (NSArray *)didReceiveNewResult:(id)result {
    NSArray *items = [super didReceiveNewResult:result];

    if([items count] >= kCount) {
        self.scrollWrapper.enableLoadMore = YES;
    } else {
        self.scrollWrapper.enableLoadMore = NO;
    }

    return items;
}

- (NSArray *)didReceiveMoreResult:(id)result {
    NSArray *items = [super didReceiveMoreResult:result];

    if([items count] >= kCount) {
        self.scrollWrapper.enableLoadMore = YES;
    } else {
        self.scrollWrapper.enableLoadMore = NO;
    }

    return items;
}


- (NSArray *)itemsFromResult:(id)result {
    NSMutableArray *items = [NSMutableArray array];

    for(NSDictionary *parameters in [result validArrayForKey:@"users"]) {
        PPFoundUserModel *user = [[PPFoundUserModel alloc] init];
        user.avatarKey = [parameters validStringForKey:@"avatar"];
        user.avatarHost = [parameters validStringForKey:@"avatarHost"];
        user.nick = [parameters validStringForKey:@"name"];
        user.account = [parameters validStringForKey:@"pickpic"];
        user.userID = [parameters validStringForKey:@"user"] ?: [parameters validStringForKey:@"id"];
        user.relationship = [parameters validNumberForKey:@"relationship"];
        [items addObject:user];
    }

    return items;
}

- (UIView *)emptyPromptViewForError:(NSError *)error {
    if(error != nil) {
        UILabel *label = [[UILabel alloc] init];
        label.text = error.networkPrompt;
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = [UIColor colorWithRGBHex:0x999999];
        [label sizeToFit];

        return label;
    } else {
        UILabel *label = [[UILabel alloc] init];
        label.text = @"搜索无结果";
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = [UIColor colorWithRGBHex:0x999999];
        [label sizeToFit];

        return label;
    }
}

- (UIEdgeInsets)preferredScrollInsets {
    return UIEdgeInsetsZero;
}

@end
